package com.atguigu.spzx.manager.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.atguigu.spzx.manager.mapper.CategoryMapper;
import com.atguigu.spzx.model.vo.product.CategoryExcelVo;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class ExcelListener<T> extends AnalysisEventListener<T> {

    private static final int BATCH_COUNT = 100;

    //批量处理（提高效率）：读100条数据，再批量往数据库写。而不是读一条往数据库写一条。
    private List<CategoryExcelVo> categoryDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    //@Autowired  不能使用自动装配。  因为ExcelListener对象不是ioc容器创建的。
    CategoryMapper categoryMapper;

    public ExcelListener(CategoryMapper categoryMapper){
        this.categoryMapper = categoryMapper;
    }

    //每读一行执行一次
    @Override
    public void invoke(T t, AnalysisContext context) {
        CategoryExcelVo categoryExcelVo = (CategoryExcelVo)t;
        categoryDataList.add(categoryExcelVo);
        if(categoryDataList.size() >= BATCH_COUNT){
            saveData();
            categoryDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    private void saveData() {
        categoryMapper.insertBatch(categoryDataList);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
    }

}
